/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.imagepipeline.producers;

import com.facebook.common.memory.PooledByteBufferFactory;
import com.facebook.imagepipeline.image.EncodedImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.oszc.bbhmlibrary.utils.LogUtil;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;

import java.io.IOException;
import java.util.concurrent.Executor;

/** Executes a local fetch from a resource. */
  public class LocalResourceFetchProducer extends LocalFetchProducer {

    private static final String TAG = LocalResourceFetchProducer.class.getSimpleName();

  public static final String PRODUCER_NAME = "LocalResourceFetchProducer";

  private final ResourceManager mResources;

  public LocalResourceFetchProducer(
      Executor executor, PooledByteBufferFactory pooledByteBufferFactory, ResourceManager resources) {
    super(executor, pooledByteBufferFactory);
    mResources = resources;
  }

  @Override
  protected EncodedImage getEncodedImage(ImageRequest imageRequest) throws IOException, NotExistException {
    return getEncodedImage(
        mResources.getResource(getResourceId(imageRequest)), getLength(imageRequest));

  }

  private int getLength(ImageRequest imageRequest) {
    Resource fd = null;
    try {
     // fd = mResources.openRawResourceFd(getResourceId(imageRequest));
      //fd = mResources.getRawFileEntry(imageRequest.getSourceUri().getLastPath().substring(1)).openRawFileDescriptor();
        fd = mResources.getResource(getResourceId(imageRequest));
      return (int) fd.available();
    } catch (IOException | NotExistException e) {
      return -1;
    } finally {
      try {
        if (fd != null) {
          fd.close();
        }
      } catch (IOException ignored) {
        // There's nothing we can do with the exception when closing descriptor.
      }
    }
  }

  @Override
  protected String getProducerName() {
    return PRODUCER_NAME;
  }

  private static int getResourceId(ImageRequest imageRequest) {
    int resId= Integer.parseInt(imageRequest.getSourceUri().getLastPath());
    LogUtil.error(TAG,"getResourceId:"+resId);
    return resId;
   // return Integer.parseInt(imageRequest.getSourceUri().getLastPath());
  }
}
